﻿//Copyright © Omega Point 2008
//All rights reserved.
//This Software is Licensed under the New BSD License
//for a full copy of this license see http://www.codeplex.com/networkmessenger/license
//Redistributions of source code must retain the above copyright notice.
using System;
using System.Collections.Generic;
using System.Text;

using System.Windows.Controls;
using System.Windows;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Media;

namespace OmegaPoint.Vista.Dwm
{
    public static class Aero
    {
        /// <summary>
        /// Extends Glass into the Window Frame (WPF)
        /// </summary>
        /// <param name="window">Window to Apply To</param>
        /// <param name="margin">Margins to Apply To (Thickness of -1 To Fill Window)</param>
        public static void ExtendGlassFrame(Window window, Thickness margin)
        {
            
                if (!DoesOSSupportDwm())
                    throw new InvalidOperationException("DWM Composition must be enabled to extend glass frame");

                IntPtr hwnd = new WindowInteropHelper(window).Handle;
                if (hwnd == IntPtr.Zero)
                    throw new InvalidOperationException("The Window must be shown before extending glass");

                window.Background = Brushes.Transparent;
                HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;

                MARGINS margins = new MARGINS(margin);
                DwmExtendFrameIntoClientArea(hwnd, ref margins);
        }       

        /// <summary>
        /// Returns whether the computer Supports DWM
        /// </summary>
        /// <returns></returns>
        public static bool DoesOSSupportDwm()
        {
            if (Environment.OSVersion.Version.Major >= 6)
            {
                if (DwmIsCompositionEnabled())
                {
                    return true;
                }
                else
                {
                    return false;
                }                
            }
            else
            {
                return false;
            }
        }

        private struct MARGINS
        {
            public int Left;
            public int Right;
            public int Top;
            public int Bottom;

            public MARGINS(Thickness t)
            {
                Left = (int)t.Left;
                Right = (int)t.Right;
                Top = (int)t.Top;
                Bottom = (int)t.Bottom;
            }
        }
        
        [DllImport("dwmapi.dll", PreserveSig = false)]
        private static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);

        [DllImport("dwmapi.dll", PreserveSig = false)]
        private static extern bool DwmIsCompositionEnabled();
    }
}
